/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.manuscripts.analysis;

import cz.mzk.rehan.commons.Dom4jUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class LocusPathsAnalyzer {

    private final Set<File> teiFiles = new HashSet<File>();
    private final Document locusPathXslt;

    public LocusPathsAnalyzer(File locusPathXslt) throws FileNotFoundException, DocumentException {
        this.locusPathXslt = Dom4jUtils.loadDocument(locusPathXslt, true);
    }

    public void addTeiFile(File teiFile) {
        teiFiles.add(teiFile);
    }

    public LocusPathsStatistics analyze() {
        LocusPathsStatistics statistics = new LocusPathsStatistics();
        for (File teiFile : teiFiles) {
            try {
                Document extractedLocusPaths = extractLocusPaths(teiFile);
                fillStatistics(statistics, extractedLocusPaths);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(LocusPathsAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(LocusPathsAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return statistics;
    }

    private Document extractLocusPaths(File teiFile) throws FileNotFoundException, DocumentException {
        Document teiDoc = Dom4jUtils.loadDocument(teiFile, false);
        return Dom4jUtils.transformDocument(teiDoc, locusPathXslt);
    }

    private void fillStatistics(LocusPathsStatistics statistics, Document extractedLocusPaths) {
        List<Node> locusNodes = extractedLocusPaths.selectNodes("//locus");
        for (Node locus : locusNodes) {
            String path = locus.getText();
            statistics.addPath(path);
        }
    }
}
